package com.puman.beautyfarmcounselor.ui.schedule;


import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.puman.beautyfarmcounselor.IndexActivity;
import com.puman.beautyfarmcounselor.R;
import com.puman.beautyfarmcounselor.http.AjaxCallBack;
import com.puman.beautyfarmcounselor.ui.schedule.adpter.DayWeekAdapter;
import com.puman.beautyfarmcounselor.ui.schedule.adpter.DayWeekInfoAdapter;
import com.puman.beautyfarmcounselor.ui.schedule.adpter.ScheduleBookCustomerAdapter;
import com.puman.beautyfarmcounselor.ui.schedule.modle.BookData;
import com.puman.beautyfarmcounselor.ui.schedule.modle.BookInfo;
import com.puman.beautyfarmcounselor.ui.schedule.modle.DayWeekInfo;
import com.puman.beautyfarmcounselor.ui.schedule.modle.Schedule;
import com.puman.beautyfarmcounselor.util.MethedUtil;
import com.puman.beautyfarmcounselor.util.XTHttp;
import com.puman.beautyfarmcounselor.util.config.GlobalData;
import com.puman.beautyfarmcounselor.util.config.RequestAddr;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;


@EFragment(R.layout.schedule_main)
public class ScheduleFragment extends Fragment {

    /**
     * UI
     */
    @ViewById(R.id.hello)
    TextView helloText;
    @ViewById(R.id.base_title)
    TextView topTitle;
    @ViewById(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @ViewById(R.id.schedule_dayofweek_gridview)
    GridView dayOfWeekGridView;
    @ViewById(R.id.schedule_dayofweek_info_gridview)
    GridView dayOfWeekInfoGridView;
    @ViewById(R.id.schedule_show_select_day)
    TextView selectDayLable;
    @ViewById(R.id.schedule_today_icon_show)
    ImageView todyaSelectIcon;

    @ViewById(R.id.list_layout)
    LinearLayout listlayout;

    /**
     * init variables
     */
    private DayWeekInfoAdapter dayWeekInfoAdapter;
    private DayWeekAdapter dayWeekAdapter;
    private String dayOfWeekArr[] = {"日", "一", "二", "三", "四", "五", "六"};

    private List<String> dayWeekInfoList = new ArrayList<String>();//day of week
    private List<DayWeekInfo> dateTime = new ArrayList<DayWeekInfo>();//datetime
    private List<BookInfo> bookInfoList = new ArrayList<BookInfo>();

    private ScheduleBookCustomerAdapter scheduleBookCustomerAdapter;


    public ScheduleFragment() {
    }

    /**
     * init variable
     */
    protected LayoutManagerType mCurrentLayoutManagerType;

    private enum LayoutManagerType {
        GRID_LAYOUT_MANAGER,
        LINEAR_LAYOUT_MANAGER
    }

    protected RecyclerView.LayoutManager mLayoutManager;
    private static final int SPAN_COUNT = 2;

    @AfterViews
    void updateView() {
        topTitle.setText("日程");
        initView();
    }

    void initView() {
        /**
         * 设置layoutmanager
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);


        dayWeekInfoAdapter = new DayWeekInfoAdapter(getActivity(), dayWeekInfoList);
        dayOfWeekInfoGridView.setAdapter(dayWeekInfoAdapter);


//        initData();
        getDayOfWeek();
        getFutureTwoWeek();
        getScheduling();
        getBookData(startTime);
    }

    /**
     * 获取排班
     */
    XTHttp xtHttp = new XTHttp();
    String url = "";
    String param = "";

    private void getScheduling() {

        param = "emp_id=" + GlobalData.counselor.getData().getEmployee_id() +
                "&start=" + startTime +
                "&end=" + endTime;
        url = RequestAddr.schedule + param;
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
//                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private Schedule schedule;

    private void getBookData(String date) {
        param = "";
        param = "emp_id=" + GlobalData.counselor.getData().getEmployee_id() +
                "&date=" + date;
        url = RequestAddr.preOrder + param;
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealBookData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
//                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void dealData(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            schedule = objectMapper.readValue(object.toString(), Schedule.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (schedule != null){
        if (schedule.isFlag()) {
//            getFutureTwoWeek();
            dayWeekAdapter = new DayWeekAdapter(getActivity(), schedule);
            dayOfWeekGridView.setAdapter(dayWeekAdapter);
            if (schedule.getData().size() != 0) {
//                schedule.getData().get(0).setIsSelect(true);
            }
            for (int i = 0; i < dateTime.size(); i++) {
                schedule.getData().get(i).setDateNo(dateTime.get(i).getDateStr());
                schedule.getData().get(i).setDateStr(dateTime.get(i).getYMD().replace(".", "-"));
            }
            schedule.getData().get(0).setIsSelect(true);
        } else {
        }
        }
    }

    private BookData bookData = new BookData();

    private void dealBookData(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
//        bookData = new BookData();
        bookData.setFlag(false);
        bookData.setMsg("");
        try {
            bookData = objectMapper.readValue(object.toString(), BookData.class);
        } catch (IOException e) {
            e.printStackTrace();
//            return;
        }
        MethedUtil.UtilLog("size:" + bookData.getData().size());
        if (bookData.isFlag()){
        }else{
            bookData.getData().clear();
        }
        if (bookData.getData().size() ==  0){
            listlayout.setVisibility(View.GONE);
        }else{
            listlayout.setVisibility(View.VISIBLE);
        }
        scheduleBookCustomerAdapter = new ScheduleBookCustomerAdapter(getActivity(), bookData);
        mRecyclerView.setAdapter(scheduleBookCustomerAdapter);
    }


    @ItemClick(R.id.schedule_dayofweek_gridview)
    void onDaySelect(int position) {
        selectDayLable.setText(dateTime.get(position).getYMD());
        if (position == 0) {
            todyaSelectIcon.setVisibility(View.VISIBLE);
        } else {
            todyaSelectIcon.setVisibility(View.GONE);
        }
        for (int i = 0; i < dateTime.size(); i++) {
            if (i == position) {
                schedule.getData().get(i).setIsSelect(true);
            } else {
                schedule.getData().get(i).setIsSelect(false);
            }
        }
        getBookData(schedule.getData().get(position).getDate());
        dayWeekAdapter.notifyDataSetChanged();

    }

    /**
     * 获取一周 星期
     */
    private void getDayOfWeek() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date(System.currentTimeMillis()));
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        dayWeekInfoList.clear();
        switch (dayOfWeek) {
            case 1:
                for (int i = 0, j = dayOfWeek - 1; i < dayOfWeekArr.length; i++, j++) {
                    dayWeekInfoList.add(dayOfWeekArr[j % dayOfWeekArr.length]);
                }
                break;
            case 2:
                for (int i = 0, j = dayOfWeek - 1; i < dayOfWeekArr.length; i++, j++) {
                    dayWeekInfoList.add(dayOfWeekArr[j % dayOfWeekArr.length]);
                }
                break;
            case 3:
                for (int i = 0, j = dayOfWeek - 1; i < dayOfWeekArr.length; i++, j++) {
                    dayWeekInfoList.add(dayOfWeekArr[j % dayOfWeekArr.length]);
                }
                break;
            case 4:
                for (int i = 0, j = dayOfWeek - 1; i < dayOfWeekArr.length; i++, j++) {
                    dayWeekInfoList.add(dayOfWeekArr[j % dayOfWeekArr.length]);
                }
                break;
            case 5:
                for (int i = 0, j = dayOfWeek - 1; i < dayOfWeekArr.length; i++, j++) {
                    dayWeekInfoList.add(dayOfWeekArr[j % dayOfWeekArr.length]);
                }
                break;
            case 6:
                for (int i = 0, j = dayOfWeek - 1; i < dayOfWeekArr.length; i++, j++) {
                    dayWeekInfoList.add(dayOfWeekArr[j % dayOfWeekArr.length]);
                }
                break;
            case 7:
                for (int i = 0, j = dayOfWeek - 1; i < dayOfWeekArr.length; i++, j++) {
                    dayWeekInfoList.add(dayOfWeekArr[j % dayOfWeekArr.length]);
                }
                break;
        }
    }

    /**
     * 获取近两周 日期
     */
    private String startTime = "";
    private String endTime = "";

    private void getFutureTwoWeek() {
        dateTime.clear();
        for (int i = 0; i < 14; i++) {
            Calendar recentWeek = Calendar.getInstance(Locale.CHINA);
            Date now=new Date();
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            recentWeek.add(Calendar.DATE, i);
            DayWeekInfo dayWeekInfo = new DayWeekInfo();
            int month = recentWeek.get(Calendar.MONTH) + 1;
            if (0 == i){
                String monthStr = String.valueOf(month);
                if (monthStr.length() == 1){
                    monthStr = "0"+monthStr;
                }
                startTime = fmt.format(now);
//               startTime = recentWeek.get(Calendar.YEAR) + "-" + monthStr + "-" + recentWeek.get(Calendar.DATE);
            }
            dayWeekInfo.setYMD(recentWeek.get(Calendar.YEAR) + "." + month + "." + recentWeek.get(Calendar.DATE));
            dayWeekInfo.setDateStr(recentWeek.get(Calendar.DATE) + "");
//            schedule.getData().get(i).setDateStr(recentWeek.get(Calendar.DATE) + "");
            if (13 == i) {
                endTime = recentWeek.get(Calendar.YEAR) + "-" + month + "-" + recentWeek.get(Calendar.DATE);
            }
            dateTime.add(dayWeekInfo);
        }
        dateTime.get(0).setIsSelected(true);
        Calendar selectDay = Calendar.getInstance(Locale.CHINA);
        selectDay.add(Calendar.DATE, 0);
        int month = selectDay.get(Calendar.MONTH) + 1;
        selectDayLable.setText(selectDay.get(Calendar.YEAR) + "." + month + "." + selectDay.get(Calendar.DATE));
        MethedUtil.UtilLog("starttime:" + startTime);

    }



}
